<?php

namespace App\Http\Controllers\Api;

use App\Http\Services\MemoService;
use App\Http\Services\RemindService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

/**
 * @property MemoService $memoService
 * @property RemindService $remindService
 */
class MemoController extends BaseController
{

    public function __construct(MemoService $memoService, RemindService $remindService)
    {
        $this->memoService = $memoService;
        $this->remindService = $remindService;
    }

    public function list(Request $request)
    {
        return $this->success($this->memoService->getList($request->all()));
    }

    public function add(Request $request)
    {
        $post = $request->post();
        $validator = Validator::make($post, [
            'title' => 'required|unique:memos,title',
            'desc' => 'required',
        ], [
            'title.required' => '标题不能为空',
            'title.unique' => '标题不能重复',
            'desc.required' => '描述不能为空',
        ]);
        if ($validator->fails()) {
            return $this->fail($validator->errors()->first());
        }

        $post['user_id'] = $request->userInfo['id'];
        $result = $this->memoService->addMemo($post);
        if (!$result) {
            return $this->fail('添加失败');
        }
        return $this->success();
    }

    public function detail(Request $request)
    {
        return $this->success($this->memoService->getDetail($request->get('id', 1)));
    }

    public function edit(Request $request)
    {
        $post = $request->post();
        $validator = Validator::make($post, [
            'title' => 'required',
            'desc' => 'required',
            'id' => 'required',
        ], [
            'title.required' => '标题不能为空',
            'id.required' => 'id不能为空',
        ]);
        if ($validator->fails()) {
            return $this->fail($validator->errors()->first());
        }

        $post['user_id'] = $request->userInfo['id'];
        $result = $this->memoService->updateMemo($post);
        if (!$result) {
            return $this->fail($result);
        }
        return $this->success();
    }

    public function delete(Request $request)
    {
        $result = $this->memoService->deleteMemo($request->get('id', 1));
        if (!$result) {
            return $this->fail('删除失败');
        }
        return $this->success();
    }

    public function top(Request $request)
    {
        $result = $this->memoService->topMemo($request->post());
        if (!$result) {
            return $this->fail('置顶失败');
        }
        return $this->success();
    }

    public function done(Request $request)
    {
        $result = $this->memoService->doneMemo($request->post());
        if (!$result) {
            return $this->fail('置顶失败');
        }
        return $this->success();
    }

}
